<?php
namespace app\controllers;

use app\models\order\Order;
use app\models\user\User;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class QueueData
{
    public function getList($user_id)
    {
        $chain = Chain::getReferrerChain($user_id, [UserLevel::$keys['vip3']]);
        $chain = ArrayHelper::getColumn($chain, 'id');

        $user = User::findOne(['id' => $user_id]);
        if ($user->level >= UserLevel::$keys['vip3']) {
            $chain = array_merge([$user_id], $chain);
        }

        // var_dump($chain);exit;

        if (empty($chain)) {
            return [];
        }

        // 从链最顶端开始
        $list = $this->go($chain[count($chain) - 1]);

        // var_dump($list);exit;

        foreach ($list as &$item) {
            $commission = $this->commissionCalc($list, $item);
            // echo $commission, "<br>";

            // 可能出现负
            if ($commission <= 0) {
                $commission = 0;
            }

            $item['commission'] = $commission;
        }

        // 如果不是此订单上的链(推荐人链条), 则需要跳过(不处理)
        foreach ($list as $key => &$item) {
            if (!in_array($key, $chain)) {
                unset($list[$key]);
            }
        }

        // var_dump($list);exit;

        return $list;
    }

    public function go($referrer_id = 0, $list = [])
    {
        $query = User::find();
        if ($referrer_id > 0) {
            $query->where(['id' => $referrer_id]);
        } else {
            return [];
        }

        $users = $query->andWhere(['level' => [UserLevel::$keys['vip3']]])
            ->orderBy(['id' => SORT_ASC])
            ->select(['id'])
            ->asArray()
            ->all();

        $users = ArrayHelper::getColumn($users, 'id');

        // var_dump($users);exit;

        // 2) 团队
        $team = [];
        foreach ($users as $user) {

            // 全部
            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            // 管理
            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip3'],
            ], ['id']);

            $manager = ArrayHelper::getColumn($manager, 'id');

            $team[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager
            ];
        }

        $users = $team;

        // 3) 业绩
        foreach ($users as $user) {
            $orders = Order::find()
                ->where(['user_id' => array_merge([$user['id']], $user['children'])])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                // 上个月的 (下个月1号返)
                // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                // todo 这里是累计的, 每个月返1次就行了
                ->all();

            $sum = 0;
            foreach ($orders as $order) {
                $sum += $order->total_pay;
            }

            $user['sum'] = $sum;
            $user['amount'] = $this->getAmount($sum);

            if (!key_exists($user['id'], $list)) {
                $list[$user['id']] = $user;
            }

            // // 子团队业务
            foreach ($user['manager'] as $item) {
                $list = $this->go($item, $list);
            }

        }

        // var_dump($list);exit;

        return $list;
    }

    protected function getAmount($sum)
    {
        if ($sum == 0) {
            return 0;
        }

        $model = ZSetting::find()
            ->where(['<=', 'start', $sum])
            ->andWhere(['>=', 'end', $sum])
            ->one();

        // echo $model->createCommand()->getRawSql();exit;

        if ($model) {
            return $model->amount;
        }

        // 最大
        $last = ZSetting::find()
            ->orderBy(['amount' => SORT_DESC])
            ->one();
        if ($sum >= $last->end) {
            return $last->amount;
        }

        return 0;
    }

    public function commissionCalc($list, $item)
    {
        // 找出需要减掉的(可能有多个)
        $data = [];
        foreach ($item['manager'] as $v) {
            $chain = Chain::getReferrerChain($v, [UserLevel::$keys['vip3']]);
            if ($chain) {

                if ($chain[0]['id'] == $item['id']) {
                    array_push($data, $v);
                }
            }
        }

        // var_dump($data);exit;

        $sub = 0;
        foreach ($list as $v) {
            if (in_array($v['id'], $data)) {
                $sub += $v['amount'];
            }
        }

        return $item['amount'] - $sub;
    }
}